package com.chenxi;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/*
使用Condition实例方法前需要先保持锁定。Lock.lock()
 */

public class MyCondition {

    private ReentrantLock lock = new ReentrantLock();
    private Condition con1 = lock.newCondition();
    private Condition con2 = lock.newCondition();

    public void await1(){
        try{
            lock.lock();
            System.out.println("await1 start : "+ System.currentTimeMillis() + " " + Thread.currentThread().getName());
            con1.await();
            System.out.println("await1 end : "+ System.currentTimeMillis() + " " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void await2(){
        try{
            lock.lock();
            System.out.println("await2 start : "+ System.currentTimeMillis() + " " + Thread.currentThread().getName());
            con2.await();
            System.out.println("await2 end : "+ System.currentTimeMillis() + " " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void signalAll_1(){
        try{
            lock.lock();
            System.out.println("signalAll_1 start : "+ System.currentTimeMillis() + " " + Thread.currentThread().getName());
            con1.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void signalAll_2(){
        try{
            lock.lock();
            System.out.println("signalAll_2 start : "+ System.currentTimeMillis() + " " + Thread.currentThread().getName());
            con2.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyCondition myCondition = new MyCondition();
        new Thread(new Runnable() {
            @Override
            public void run() {
                myCondition.await1();
            }
        }, "aaa").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                myCondition.await2();
            }
        },"bbb").start();
        Thread.sleep(3000);
        myCondition.signalAll_1();
    }
}
